import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:window_manager/window_manager.dart';
import 'package:yuellyfactory/MainPageVC.dart';
import 'package:yuellyfactory/util/AuthUtil.dart';

import 'package:yuellyfactory/util/BaseRequest.dart';
import 'dart:io';

import 'package:yuellyfactory/util/CustomAnimation.dart';
import 'package:yuellyfactory/util/StorageUtil.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/util/ViewUtil.dart';


Future<void> main() async{
  configLoading();
  await GetStorage.init();
  WidgetsFlutterBinding.ensureInitialized();
  if(Platform.isWindows){
    await windowManager.ensureInitialized();
    WindowOptions windowOptions = const WindowOptions(
      size: Size(1200, 800),
      center: true,
      backgroundColor: Colors.transparent,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.hidden,
      windowButtonVisibility: true

    );
    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();


    });

  }

  //顶部透明
  if (Platform.isAndroid){
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle.light.copyWith(
        statusBarColor: Colors.transparent,//状态栏背景颜色，
        statusBarIconBrightness: Brightness.dark,//状态栏字体颜色（黑色）
      ),
    );
  }
  runApp(const MyApp());
}
void configLoading() {
  //对话框配置
  EasyLoading.instance
    ..displayDuration = const Duration(milliseconds: 2000)
    ..indicatorType = EasyLoadingIndicatorType.threeBounce
    ..loadingStyle = EasyLoadingStyle.dark
    ..indicatorSize = 20.0
    ..radius = 10.0
  // ..progressColor = Colors.yellow
  // ..backgroundColor = Colors.white
  // ..indicatorColor = Colors.white
    ..textColor = Colors.white
    ..maskColor = Colors.blue.withOpacity(0.5)
    ..userInteractions = false //后面不可点击
    ..dismissOnTap = false     //点击关闭
    ..customAnimation = CustomAnimation();
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return
      ScreenUtilInit(
        designSize: const Size(1920,1280),
        minTextAdapt: true,
        builder: (context, child) {
          return

            ShadApp.custom(
              themeMode: ThemeMode.dark,
              darkTheme: ShadThemeData(
                brightness: Brightness.light,
                colorScheme: const ShadSlateColorScheme.light(

                ),
                primaryButtonTheme: const ShadButtonTheme(
                  backgroundColor: Colors.blue,
                )
              ),
              appBuilder: (context,themeData) {
                return GetMaterialApp(
                  locale: Get.deviceLocale,
                  title: '',
                  theme: ThemeData(
                    colorScheme: ColorScheme.fromSeed(seedColor: Colors.black),
                    useMaterial3: true,
                  ),
                  home: child,
                  debugShowCheckedModeBanner: false,
                  builder: EasyLoading.init(
                    builder: (context, child) {
                      return MediaQuery(
                        // 设置字体不跟随系统变化
                        data: MediaQuery.of(context).copyWith(textScaler: const TextScaler.linear(1.0)),
                        child: child ?? Container(),
                      );
                    },
                  ),
                );
              },
            );

        },
        child: const MyHomePage(title: ''),
      );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  TextEditingController accountController = TextEditingController();
  TextEditingController pwdController = TextEditingController();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();


    if (StorageUtil.checkLogin()) {
      AuthUtil.instance.initDatas();
      Future.delayed(const Duration(milliseconds: 500)).then((value) {
        Get.off(const MainPageVC());
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        extendBodyBehindAppBar: true,
        body: Stack(
          children: [
            ViewUtil.defalutWhiteBg(context),
            ViewUtil.defaultTopBg(context),
            //中间的数据
            Positioned(
              //状态栏+appbar高度
              top: ScreenUtil().statusBarHeight + kToolbarHeight,
              bottom: ViewUtil.screenHeight(185),
              left: ViewUtil.screenWidth(300),
              right: ViewUtil.screenWidth(300),
              child:
              SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SizedBox(height: ViewUtil.screenHeight(100),),
                    Image.asset(
                      'images/logo.png', width: ViewUtil.screenWidth(200),),
                    if(!StorageUtil.checkLogin())
                    SizedBox(height: ViewUtil.screenHeight(100),),
                    if(!StorageUtil.checkLogin())
                    Container(
                      height: ViewUtil.screenHeight(100),
                      width: ViewUtil.matchWidth(context) -
                          ViewUtil.screenWidth(180),
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: ViewUtil.screenWidth(60)),
                      decoration: BoxDecoration(
                        color: const Color(0xffF4F6FA),
                        borderRadius: BorderRadius.circular(ViewUtil.radio(12)),
                      ),
                      child:
                      Row(

                        children: [

                          Image.asset('images/login_account.png',
                            width: ViewUtil.screenWidth(50),),
                          SizedBox(width: ViewUtil.screenWidth(80),),
                          Expanded(child: TextField(
                            controller: accountController,
                            maxLines: 1,
                            style: TextStyle(color: const Color(0xFF303C52),
                                fontSize: ViewUtil.fontSize(32)),
                            decoration: InputDecoration(
                              //垂直居中
                              isCollapsed: true,
                              hintText: '登录账号',
                              border: InputBorder.none,
                              hintStyle: const TextStyle(
                                  color: Color(0xFFB7B7B7)),
                            ),
                          ),),

                        ],
                      ),


                    ),
                    if(!StorageUtil.checkLogin())
                    SizedBox(height: ViewUtil.screenHeight(40),),
                    if(!StorageUtil.checkLogin())
                    Container(
                      height: ViewUtil.screenHeight(100),
                      width: ViewUtil.matchWidth(context) -
                          ViewUtil.screenWidth(180),
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: ViewUtil.screenWidth(60)),
                      decoration: BoxDecoration(
                        color: const Color(0xffF4F6FA),
                        borderRadius: BorderRadius.circular(ViewUtil.radio(12)),
                      ),
                      child:
                      Row(

                        children: [

                          Image.asset('images/login_pwd.png',
                            width: ViewUtil.screenWidth(50),),
                          SizedBox(width: ViewUtil.screenWidth(80),),
                          Expanded(child: TextField(
                            controller: pwdController,
                            maxLines: 1,
                            obscureText: true,
                            style: TextStyle(color: const Color(0xFF303C52),
                                fontSize: ViewUtil.fontSize(32)),
                            decoration: InputDecoration(
                              //垂直居中
                              isCollapsed: true,
                              hintText: '请输入密码',
                              border: InputBorder.none,
                              hintStyle: const TextStyle(
                                  color: Color(0xFFB7B7B7)),
                            ),
                          ),),

                        ],
                      ),


                    ),
                    if(!StorageUtil.checkLogin())
                    SizedBox(height: ViewUtil.screenHeight(120),),
                    if(!StorageUtil.checkLogin())
                    ViewUtil.textButton(
                        '登录',
                        ViewUtil.screenWidth(600),
                        ViewUtil.screenHeight(40),
                        ViewUtil.radio(12),
                        const Color(0xfff4f4f4),
                        const Color(0xfff4f4f4),
                        const Color(0xff72747A),
                        ViewUtil.fontSize(32), () {
                      toLogin();
                    })
                  ],
                ),
              ),
            ),

          ],

        ),
      );
  }

  void toLogin() {
    var account = accountController.text;
    var pwd = pwdController.text;
    if (account.isEmpty) {
      ToastUtil.showToast('请输入正确账号');
      return;
    }
    if (pwd.isEmpty) {
      ToastUtil.showToast('请输入密码');
      return;
    }
    BaseRequest.postHttp("user/login",
        parameters: {"username": account, "password": pwd}
        ,
        canTip: true,
        context: context,
        onSuccess: (data) async {
          bool result = BaseRequest.chekResponse(data, true);
          if (result) {
            var v = data["data"];
            var token = v["token"];
            var userId = v["userId"];
            var username = v["username"];
            var roleName = v["roleName"];
            var roleCode = v["roleCode"];
            var disCount = v["discount"];
            var menusApp=v["menusApp"];
            var buttonsApp=v["buttonsApp"];
            StorageUtil.saveDiscount(disCount.toString());
            StorageUtil.saveUserName(username);
            StorageUtil.saveToken(token);
            StorageUtil.saveLoginAccount(account);
            StorageUtil.saveRoleName(roleName);
            StorageUtil.saveUserId(userId);
            StorageUtil.saveRoleCode(roleCode);
            StorageUtil.saveMenu(menusApp);
            StorageUtil.saveMenuButton(buttonsApp);
            ToastUtil.showToast('登录成功');
            AuthUtil.instance.initDatas();
            Get.off(const MainPageVC());
          }
        },
        onError: (error) {});
  }

}
